package com.movitech.mobile.cz.base.common.util;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

public class JpegGenerator {

	public static void generate(String fileName, int width, int height, int pixSize) throws Exception {
		int x, y = 0;

		BufferedImage bi = new BufferedImage(pixSize * width, pixSize * height, BufferedImage.TYPE_3BYTE_BGR);

		Graphics2D g = (Graphics2D) bi.getGraphics();

		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				x = i * pixSize;
				y = j * pixSize;

				if ((i * j) % 6 == 0) {
					g.setColor(Color.GRAY);
				} else if ((i + j) % 5 == 0) {
					g.setColor(Color.BLUE);
				} else {
					g.setColor(Color.WHITE);
				}

				g.fillRect(y, x, pixSize, pixSize);

			}

		}

		g.dispose();

		saveToFile(bi, new File(fileName));

	}

	/**
	 * Saves jpeg to file
	 */

	@SuppressWarnings("rawtypes")
	public static void saveToFile(BufferedImage img, File file) throws IOException {

		ImageWriter writer = null;

		java.util.Iterator iter = ImageIO.getImageWritersByFormatName("jpg");

		if (iter.hasNext()) {
			writer = (ImageWriter) iter.next();
		}

		ImageOutputStream ios = ImageIO.createImageOutputStream(file);

		writer.setOutput(ios);

		ImageWriteParam param = new JPEGImageWriteParam(java.util.Locale.getDefault());

		param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

		param.setCompressionQuality(0.98f);

		writer.write(null, new IIOImage(img, null, null), param);

	}

}